package com.fancy.service.impl;

import com.fancy.pojo.JpaUser;
import com.fancy.pojo.UserReq;
import com.fancy.repository.ILoginRepository;
import com.fancy.service.ILoginService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {

    @Resource
    ILoginRepository loginRepository;
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    RabbitTemplate rabbitTemplate;

    @Override
    public String login(JpaUser jpauser) {

        JpaUser byUserName = loginRepository.findByUserName(jpauser.getUserName());
        if (byUserName==null){
            return "没有该用户";
        }else if (!byUserName.getUserPassword().equals(jpauser.getUserPassword())){
            return "密码错误";
        }
        UUID token = UUID.randomUUID();
        redisTemplate.opsForValue().set(token.toString(),byUserName);

        redisTemplate.expire(token.toString(),30, TimeUnit.MINUTES);
        System.out.println(token.toString());

        return token.toString();
    }

    @Override
    public String sendMail(String s) {
        //去数据库校验是否为唯一值
        JpaUser byUserName = loginRepository.findByUserName(s);
        if (byUserName!=null){
            return "用户邮箱已注册";
        }
        Map map = new HashMap<>();
        map.put("email",s);
        rabbitTemplate.convertAndSend("fancy-music-email",map);
        return "发送成功";
    }

    @Override
    public String registry(UserReq userReq) {
        String email = userReq.getUserEmail();
        Object o = redisTemplate.opsForValue().get(email);
        if (o!=null){
            String code = userReq.getCode();
            if (o.toString().equals(code)){
                //验证码比对通过，加入到数据库，用户注册成功
                JpaUser jpaUser = new JpaUser();
                jpaUser.setUserName(userReq.getUserName());
                BeanUtils.copyProperties(userReq,jpaUser);
                loginRepository.save(jpaUser);
                return "注册成功";
            }else{
                return "验证码错误";
            }
        }
        return "验证码超时";
    }
}
